<template lang="pug">
.register 注册
  el-form.form(
    :model="registerForm",
    label-width="80px",
    :rules="ruleValidate",
    ref="registerFormRef"
  )
    el-form-item(label="用户名", prop="username")
      el-input(v-model="registerForm.username")
    el-form-item(label="密码", prop="password")
      el-input(v-model="registerForm.password", show-password)
    el-form-item(label="确认密码", prop="rePassword")
      el-input(v-model="registerForm.rePassword", show-password)
    el-form-item.btn-team
      el-button(@click="back") 返回
      el-button(type="primary", @click="register") 注册
</template>

<script>
export default {
  data() {
    var pwdCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.rePassword !== "") {
          this.$refs.registerFormRef.validateField(this.registerForm.password);
        }
        callback();
      }
    };
    var pwdAgainCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      registerForm: {
        username: "",
        password: "",
        rePassword: "",
      },
      ruleValidate: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [{ required: true, validator: pwdCheck, trigger: "blur" }],
        rePassword: [
          { required: true, validator: pwdAgainCheck, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    register() {
      const newUser = {}
      newUser.username = this.registerForm.username
      newUser.password = this.$md5(this.registerForm.password)
      this.$http.post('/register', newUser).then(
        res => {
          if(res) {
            res
            this.$message({
              type: 'success',
              message: '注册成功'
            })
            this.$router.push('/login')
          }
        }
      )
    },
  },
};
</script>

<style lang="less" scoped>
.register {
  position: absolute;
  width: 450px;
  height: 350px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 20px 10px;
  border-radius: 20px;
  border: solid 1px #777;
  box-shadow: 0 0 5px #777;
  .form {
    position: absolute;
    width: 420px;
    top: 50%;
    transform: translateY(-50%);
    .btn-team {
      position: relative;
      right: -90px;
    }
  }
}
</style>